<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getMyInfo, updateRealName } from '@/api/me'
import NavBar from '@/components/NavBar.vue'
import { useUserStore } from '@/stores/user'

const { userInfo, setUserInfo } = useUserStore()
const myInfoFormRef = ref(null)
const myInfoForm = ref({
  realName: '',
  phone: '',
})
const myInfoFormRules = {
  realName: [{ required: true, message: '请输入昵称' }],
}

async function onGetMyInfo() {
  const { result } = await getMyInfo()
  return result
}

const confirmVisible = ref(false)
function onValidate() {
  myInfoFormRef.value.validate().then(({ valid }) => {
    if (valid)
      confirmVisible.value = true
  })
}

async function onConfirm() {
  try {
    await uni.showLoading({ title: '请稍后' })
    const { success, message } = await updateRealName(myInfoForm.value.realName)
    if (!success)
      throw new Error(message)

    const res = await onGetMyInfo()
    setUserInfo(res)
    confirmVisible.value = false
    uni.hideLoading()
    await uni.showToast({ icon: 'success', title: '修改成功', duration: 1000 })

    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: '修改失败' })
  }
}

onLoad(() => {
  myInfoForm.value.realName = userInfo.realName
  myInfoForm.value.phone = userInfo.phone
})
</script>

<template>
  <view class="container h-screen">
    <NavBar title="基本信息" title-color="#fff" />
    <main class="px-3 mt-5">
      <view class="mb-4.5 text-[#666] center">
        <image class="h-120 w-120" src="../../static/image/me/default-avatar.png" />
      </view>
      <view class="bg-white rounded-xl shadow overflow-hidden">
        <nut-config-provider :theme-vars="{ cellBoxShadow: 'none', cellAfterBorderBottom: '1px solid #ccc' }">
          <nut-form ref="myInfoFormRef" :model-value="myInfoForm" :rules="myInfoFormRules">
            <nut-form-item prop="realName">
              <nut-input v-model="myInfoForm.realName" placeholder="请输入昵称" type="text" />
            </nut-form-item>
            <nut-form-item prop="phone">
              <nut-input v-model="myInfoForm.phone" disabled placeholder="请输入手机号" type="digit" />
            </nut-form-item>
            <nut-form-item>
              <view class="pb-12.5 pt-11">
                <nut-button
                  block
                  custom-color="linear-gradient(to right, #F89201, #F83600)"
                  @click="onValidate"
                >
                  修改
                </nut-button>
              </view>
            </nut-form-item>
          </nut-form>
        </nut-config-provider>
      </view>
    </main>
    <nut-dialog v-model:visible="confirmVisible" content="确认修改信息吗?" @ok="onConfirm" />
  </view>
</template>

<style scoped>
.container {
  background-image: linear-gradient(to bottom, #fba414 10%, white 40%);
}
</style>
